<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">

                <el-input v-model="query.userAcct" placeholder="账号" class="handle-input mr10"
                          @keyup.enter.native="handleSearch" style="width: 180px"></el-input>
                <el-input v-model="query.userNm" placeholder="姓名" class="handle-input mr10"
                          @keyup.enter.native="handleSearch" style="width: 180px"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="el-button" icon="el-icon-delete" @click="handleReset">重置</el-button>
                <div class="right-items" style="float: right;">
                    <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                </div>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column prop="userAcct" label="账号" align="center"></el-table-column>
                <el-table-column prop="userNm" label="姓名" align="center"></el-table-column>
                <el-table-column prop="roleNms" label="角色名称" align="center"></el-table-column>
                <el-table-column prop="userPhone" label="手机号" align="center"></el-table-column>
                <el-table-column prop="userSexText" label="性别" align="center"></el-table-column>
                <!--                <el-table-column label="头像(查看大图)" align="center" width="68">-->
                <!--                    <template slot-scope="scope">-->
                <!--                        <el-image-->
                <!--                                class="table-td-thumb"-->
                <!--                                :src="'data:image/'+ scope.row.imgTp +';base64,' + scope.row.imgData"-->
                <!--                                 @click="onPreview('data:image/'+ scope.row.imgTp +';base64,' + scope.row.imgData)"></el-image>-->
                <!--                        <el-image-viewer-->
                <!--                                v-if="showViewer"-->
                <!--                                :on-close="closeViewer"-->
                <!--                                :url-list="srcList" />-->
                <!--                    </template>-->
                <!--                </el-table-column>-->
                <el-table-column prop="istTm" label="插入时间" align="center" sortable></el-table-column>
                <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-setting"
                                @click="reset(scope.$index, scope.row)"
                        >重置密码
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="70%" :before-close="closeAdd">
            <el-form ref="addForm" :rules="addFormRules" :model="addForm" label-width="90px">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="账号:" prop="userAcct">
                            <el-input v-model="addForm.userAcct"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="姓名:" prop="userNm">
                            <el-input v-model="addForm.userNm"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="密码:" prop="userPwd">
                            <el-input type="password" v-model="addForm.userPwd"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="10">
                        <el-form-item label="确认密码:" prop="userQPwd">
                            <el-input type="password" v-model="addForm.userQPwd"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="性别:" prop="userSex">
                            <el-select v-model="addForm.userSex" placeholder="请选择性别" style="width: 452px">
                                <el-option key="00" label="男" value="00"></el-option>
                                <el-option key="01" label="女" value="01"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="邮箱:" prop="userMail">
                            <el-input v-model="addForm.userMail"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="手机号:" prop="userPhone">
                            <el-input v-model="addForm.userPhone"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="角色名称:" prop="roleIds">
                            <el-select v-model="addForm.roleIds" placeholder="请选择角色" style="width: 452px">
                                <el-option v-for="role in roles" :label="role.roleNm" :key="role.roleId"
                                           :value="role.roleId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAdd">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="70%" :before-close="closeEdit">
            <el-form ref="editForm" :rules="editFormRules" :model="editForm" label-width="90px">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="账号:" prop="userAcct">
                            <el-input disabled v-model="editForm.userAcct"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="姓名:" prop="userNm">
                            <el-input v-model="editForm.userNm"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10">
                        <el-form-item label="性别:" prop="userSex">
                            <el-select v-model="editForm.userSex" placeholder="请选择性别" style="width: 452px">
                                <el-option key="00" label="男" value="00"></el-option>
                                <el-option key="01" label="女" value="01"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="邮箱:" prop="userMail">
                            <el-input v-model="editForm.userMail"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="手机号:" prop="userPhone">
                            <el-input v-model="editForm.userPhone"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="角色名称:" prop="roleIds">
                            <el-select v-model="editForm.roleIds" placeholder="请选择角色" style="width: 452px">
                                <el-option v-for="role in roles" :label="role.roleNm" :key="role.roleId"
                                           :value="role.roleId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeEdit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {userData, doAdd, isNotExists, doDelete, isPwdTrue, doUpdate, selectByAcct, reset} from '../api/user';
    import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
    import {getRoles} from '../api/role';

    export default {
        name: 'user',
        data() {
            return {
                query: {
                    userNm: '',
                    userAcct: '',
                    pageIndex: 1,
                    pageSize: 10
                },
                tableData: [],
                multipleSelection: [],
                editVisible: false,
                addVisible: false,
                isUpdateImg: false,
                pageTotal: 0,
                addForm: {},
                editForm: {},
                idx: -1,
                id: -1,
                isExistQuery: {
                    userAcct: '',
                },
                imgLen: '',
                /*                imgStrEdit:require('../../../../assets/upload.png'),*/
                imgLenEdit: '',
                addFormRules: {
                    userAcct: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                        {pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文', trigger: 'blur'},
                        {pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号', trigger: 'blur'},
                        {pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母', trigger: 'blur'},
                        {min: 6, max: 6, message: '账号必须为6位字符', trigger: 'blur'}
                    ],
                    userPwd: [
                        {required: true, message: '请输入用户密码', trigger: 'blur'},
                        {pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文', trigger: 'blur'},
                        {pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号', trigger: 'blur'},
                        {pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母', trigger: 'blur'},
                        {min: 6, max: 6, message: '密码必须为6位字符', trigger: 'blur'}
                    ],
                    userQPwd: [
                        {required: true, message: '请输入确认密码', trigger: 'blur'},
                        {pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文', trigger: 'blur'},
                        {pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号', trigger: 'blur'},
                        {pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母', trigger: 'blur'},
                        {min: 6, max: 6, message: '密码必须为6位字符', trigger: 'blur'}
                    ],
                    userNm: [
                        {required: true, message: '请输入用户姓名', trigger: 'blur'}
                    ],
                    roleIds: [
                        {required: true, message: '请选择角色', trigger: 'change'}
                    ],
                },
                editFormRules: {
                    userAcct: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                        {pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文', trigger: 'blur'},
                        {pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号', trigger: 'blur'},
                        {pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母', trigger: 'blur'},
                        {min: 6, max: 6, message: '账号必须为6位字符', trigger: 'blur'}
                    ],
                    userNm: [
                        {required: true, message: '请输入用户姓名', trigger: 'blur'}
                    ],
                    roleIds: [
                        {required: true, message: '请选择角色', trigger: 'change'}
                    ],
                },
                roles: [],
                showViewer: false,
                srcList: [],
            };
        },
        created() {
            this.getData();
        },
        components: {
            ElImageViewer
        },
        methods: {
            onPreview(data) {
                this.showViewer = true
                this.srcList[0] = data;
            },
            closeViewer() {
                this.showViewer = false
            },
            // 获取后台数据
            getData() {
                userData(this.query).then(res => {
                    if (res.success == true) {
                        this.tableData = res.data;
                        this.pageTotal = res.total;
                    } else {
                        this.$message.error("查询失败！");
                        this.tableData = [];
                        this.pageTotal = 0;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 触发重置按钮
            handleReset() {
                this.query.userNm = "";
                this.query.userAcct = "";
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        //后台进行删除操作
                        let condition = {
                            userAcct: row.userAcct
                        };
                        doDelete(condition).then(res => {
                            if (res.data == 1) {
                                this.$message.success('删除成功');
                                this.getData();
                            } else {
                                this.$message.error('删除失败');
                                this.getData();
                            }
                        });
                    })
                    .catch(() => {
                        this.$message({
                            message: '已取消删除'
                        });
                    });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 新增操作
            handleAdd() {
                /*  this.imgStr = require('../../../../assets/upload.png');*/
                this.addForm = {};
                getRoles().then(res => {
                    this.roles = res.data;
                });
                this.addVisible = true;
            },
            /*新增用户*/
            saveAdd() {
                // console.log("------头像大小---",this.imgLen);
                // console.log("----头像data",this.imgStr);
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        //判断输入的密码和确认密码是否一致
                        if (this.addForm.userPwd != this.addForm.userQPwd) {//不一致
                            this.$message.error("请确认两次输入的密码是否一致？");
                        } else {//一致
                            let isExistQuery = {//判断证件类型证件号是否存在条件
                                userAcct: this.addForm.userAcct
                            };
                            isNotExists(isExistQuery).then(isNotExistsres => {
                                if (isNotExistsres.data) {//用户不存在
                                    /*if (this.imgStr!=="static/img/upload.466ec9ef.png"){
                                        // 给addForm中设置对应图片属性  imgTp,imgData，imgLen
                                        //截取字符串
                                        let imgTp=this.imgStr.substring(this.imgStr.indexOf("/")+1,this.imgStr.indexOf(";"));
                                        let imgData=this.imgStr.substring(this.imgStr.indexOf(",")+1);
                                        this.addForm.imgTp=imgTp;
                                        this.addForm.imgData=imgData;
                                        this.addForm.imgLen=this.imgLen;
                                    }else{
                                        console.log("进来了----");
                                        this.addForm.imgTp="jpg";
                                        const data="";
                                        this.addForm.imgData=data;
                                        this.addForm.imgLen="74975";
                                    };*/
                                    //新增form表单提交到后台
                                    doAdd(this.addForm).then(res => {
                                        if (res.data == 1) {
                                            this.addVisible = false;
                                            this.addForm = {};
                                            this.getData();
                                            this.$message.success('保存成功');
                                        } else {
                                            this.$message.error('保存失败');
                                        }
                                    });
                                } else {//用户已存在
                                    this.$message.error('该账号已存在，请修改');
                                }
                            });
                        }
                    }
                });
            },
            closeAdd() {//关闭新增弹出框
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.addVisible = false;
                        this.addForm = {};
                        this.getData();
                    })
                    .catch(() => {
                        this.$message({
                            message: '已取消操作'
                        });
                    });
            },
            // 编辑操作
            async handleEdit(index, row) {
                this.idx = index;
                await selectByAcct({userAcct: row.userAcct}).then(res => {
                    if (res.success == true) {
                        this.editForm = res.data;
                        this.editForm.userPwd = "";
                        // if (row.imgTp!=="" || row.imgData !==""){//有头像
                        //     this.imgStrEdit="data:image/"+ this.editForm.imgTp +";base64," + this.editForm.imgData;
                        // }else{
                        //     this.imgStrEdit="static/img/upload.466ec9ef.png";
                        // }
                        getRoles().then(res => {
                            this.roles = res.data;
                        });
                        this.editVisible = true;
                    } else {
                        this.$message.error('查询失败');
                    }
                });
            },
            closeEdit() {//关闭编辑弹出框
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.editVisible = false;
                        this.editForm = {};
                        this.getData();
                    })
                    .catch(() => {
                        this.$message({
                            message: '已取消操作'
                        });
                    });
            },
            //重置密码
            reset(index, row) {
                reset({userAcct: row.userAcct}).then(res => {
                    if (res.success == true && res.data == 1) {
                        this.$message.success('重置成功');
                    } else {
                        this.$message.error('重置失败');
                    }
                });
            },
            // 保存编辑
            saveEdit() {
                this.$refs['editForm'].validate((valid) => {
                    if (valid) {   //form表单提交到后台
                        // let queryEdit = {
                        //     userAcct: this.editForm.userAcct,
                        //     userPwd: this.editForm.userPwd
                        // };
                        /* //判断img是否是初始化的
                         if (this.isUpdateImg == true && this.imgStrEdit !== "static/img/upload.466ec9ef.png") {
                             let imgTpEdit = this.imgStrEdit.substring(this.imgStrEdit.indexOf("/") + 1, this.imgStrEdit.indexOf(";"));
                             let imgDataEdit = this.imgStrEdit.substring(this.imgStrEdit.indexOf(",") + 1);
                             this.editForm.imgTp = imgTpEdit;
                             this.editForm.imgData = imgDataEdit;
                             this.editForm.imgLen = this.imgLenEdit;
                         }*/
                        doUpdate(this.editForm).then(res => {
                            if (res.data == 1) {
                                this.editVisible = false;
                                this.editForm = {};
                                this.getData();
                                this.$message.success('编辑成功');
                            } else {
                                this.$message.error('编辑失败');
                            }
                        });
                    }
                });
            },
            /*表单重置*/
            resetForm(refname) {
                if (this.$refs[refname] !== undefined) {
                    this.$refs[refname].resetFields();
                }
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
        /*border-radius 属性允许您为元素添加圆角边框！*/
        border-radius: 6px;
        background-clip: padding-box;
        border-top-left-radius: 6px;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
        border-bottom-left-radius: 6px;
    }

    /*头像上传*/
    .user-header {
        position: relative;
        display: inline-block;
    }

    .user-header-com {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        display: inline-block;
    }

    .header-upload-btn {
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        /* 通过定位把input放在img标签上面，通过不透明度隐藏 */
    }
</style>
